package com.woniu.service.impl;

import com.woniu.outlet.dao.UserPoMapper;
import com.woniu.outlet.po.UserPo;
import com.woniu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserPoMapper userPoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<UserPo> userList = userPoMapper.getUserList(username);
        if (userList == null || userList.size() == 0) {
//            throw new UsernameNotFoundException("用户未找到");
            throw null;
        } else {
            List<String> percodes = userPoMapper.getPercodeByUsername(username);
            List<GrantedAuthority> authorities = new ArrayList<>();
            percodes.forEach(percode -> {
                authorities.add(new SimpleGrantedAuthority(percode));
            });
            if (userList.get(0).getStatus().equals("0")) {

                UserDetails userDetails =
                        new org.springframework.security.core.userdetails.User(userList.get(0).getUsername(),
                                userList.get(0).getPassword(), true, true, true, false, authorities);
                return userDetails;
            } else {
                UserDetails userDetails =
                        new org.springframework.security.core.userdetails.User(userList.get(0).getUsername(),
                                userList.get(0).getPassword(), authorities);
                return userDetails;
            }
        }
    }
}
